package com.zhongfl.crm.service.impl.boss;

import com.zhongfl.crm.enums.boss.*;
import com.zhongfl.crm.exception.CRMException;
import com.zhongfl.crm.lixiao.mapper.OrderMemorandumMapper;
import com.zhongfl.crm.model.LxUser;
import com.zhongfl.crm.model.boss.*;
import com.zhongfl.crm.service.LxUserService;
import com.zhongfl.crm.service.boss.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.heptagram.channel.api.common.AssertUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 备忘录 服务类
 *
 * @author tiantian
 * @date 2018/6/13 18:06
 */
@Service
@Slf4j
public class OrderMemorandumServiceImpl implements OrderMemorandumService {

    @Resource
    private OrderMemorandumMapper orderMemorandumMapper;

    @Resource
    private LxUserService lxUserService;

    @Resource
    private AttachmentService attachmentService;

    @Resource
    private OrderService orderService;

    @Resource
    private MessageSendTaskService messageSendTaskService;

    @Resource
    private OrderAttachmentService orderAttachmentService;

    @Override
    public Long saveSystemLog(OrderMemorandum systemLog) {
        AssertUtils.notNull(systemLog.getOrderNo(), "订单号为空！");
        AssertUtils.notNull(systemLog.getStaffName(), "创建人为空！");
        AssertUtils.hasText(systemLog.getContent(), "内容为空！");

        Order deliveryOrder = orderService.findByOrderNo(systemLog.getOrderNo());
        systemLog.setStaffLabel(deliveryOrder.getDeliverManagerAmibaName());
        systemLog.setCustomerOrderNo(deliveryOrder.getCustomerOrderNo());

        systemLog.setType(OrderMemorandumTypeEnum.LOG);
        systemLog.setSyncStatus(OrderMemorandumSyncStatusEnum.SUCCESS_SYNC);

        resolveAvatarUrl(systemLog);

        orderMemorandumMapper.insert(systemLog);
        return systemLog.getId();
    }

    private void resolveAvatarUrl(OrderMemorandum orderMemorandum) {
        if (StringUtils.isNotEmpty(orderMemorandum.getAvatarUrl())) {
            return;
        }

        if (StringUtils.isNotEmpty(orderMemorandum.getStaffCode())) {
            LxUser lxUser = lxUserService.findByStaffCode(orderMemorandum.getStaffCode());
            if (Objects.nonNull(lxUser)) {
                orderMemorandum.setAvatarUrl(lxUser.getAvatarUrl());
            }
        }
    }

    @Override
    public Long save(OrderMemorandum saveInfo) {
        AssertUtils.notNull(saveInfo.getOrderNo(), "订单号为空！");
        AssertUtils.notNull(saveInfo.getStaffName(), "创建人为空！");
        AssertUtils.hasText(saveInfo.getContent(), "内容为空！");
        AssertUtils.notNull(saveInfo.getType(), "记录类型为空！");

        Order deliveryOrder = orderService.findByOrderNo(saveInfo.getOrderNo());
        if (Objects.nonNull(deliveryOrder)) {
            saveInfo.setOrderStatus(deliveryOrder.getStatus());
            saveInfo.setCustomerOrderNo(deliveryOrder.getCustomerOrderNo());
            saveInfo.setStaffLabel(deliveryOrder.getDeliverManagerAmibaName());
        }

        LxUser lxUser = lxUserService.findByStaffCode(saveInfo.getStaffCode());
        if (Objects.nonNull(lxUser)) {
            saveInfo.setAvatarUrl(lxUser.getAvatarUrl());
        }
        saveInfo.setSyncStatus(OrderMemorandumSyncStatusEnum.UN_SYNC);
        saveInfo.setAtNoticeSendStatus(OrderMemorandumAtNoticeSendStatusEnum.UN_SEND);

        orderMemorandumMapper.insert(saveInfo);

        if (Objects.nonNull(saveInfo.getImgList()) && saveInfo.getImgList().size() > 0) {
            this.upload(saveInfo);
        }

        this.saveNotifyTaskByResource(saveInfo);

        return saveInfo.getId();
    }

    /**
     * 更新
     *
     * @param record
     */
    @Override
    public void updateById(OrderMemorandum record) {
        AssertUtils.notNull(record.getId(), "id为空！");
        AssertUtils.hasText(record.getModifiedBy(), "修改人为空！");

        orderMemorandumMapper.updateById(record);
    }

    @Override
    public void updateCustomerOrderNoByOrderNo(String orderNo, String customerOrderNo) {
        AssertUtils.notNull(orderNo, "订单号为空！");
        AssertUtils.notNull(customerOrderNo, "客户订单号为空！");
        orderMemorandumMapper.updateCustomerOrderNoByOrderNo(orderNo, customerOrderNo);
    }

    @Override
    public OrderMemorandum findById(Long id) {
        return orderMemorandumMapper.selectById(id.intValue());
    }

    /**
     * 更新同步状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateSyncStatus(Long id, OrderMemorandumSyncStatusEnum status) {
        AssertUtils.notNull(id, "id为空！");
        AssertUtils.notNull(status, "状态为空！");

        orderMemorandumMapper.updateSyncStatus(id, status);
    }

    /**
     * 更新消息发送状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateAtNoticeSendStatus(Long id, OrderMemorandumAtNoticeSendStatusEnum status) {
        AssertUtils.notNull(id, "id为空！");
        AssertUtils.notNull(status, "状态为空！");

        orderMemorandumMapper.updateAtNoticeSendStatus(id, status);
    }

    @Override
    public Long saveCustomerOrderSystemLog(OrderMemorandum systemLog) {
        AssertUtils.notNull(systemLog.getOrderNo(), "订单号为空！");
        AssertUtils.notNull(systemLog.getStaffName(), "创建人为空！");
        AssertUtils.hasText(systemLog.getContent(), "内容为空！");

        systemLog.setStaffLabel(systemLog.getStaffName());
        systemLog.setCustomerOrderNo(systemLog.getCustomerOrderNo());

        systemLog.setType(OrderMemorandumTypeEnum.LOG);
        systemLog.setSyncStatus(OrderMemorandumSyncStatusEnum.SUCCESS_SYNC);

        resolveAvatarUrl(systemLog);

        orderMemorandumMapper.insert(systemLog);
        return systemLog.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(OrderMemorandum request) {
        AssertUtils.notNull(request, "文件为空！");
        AssertUtils.notNull(request.getId(), "跟进记录ID错误");
        if (org.springframework.util.CollectionUtils.isEmpty(request.getImgList())) {
            throw new CRMException("要先上传图片");
        }
        for (String filePath : request.getImgList()) {
            attachmentService.save(filePath, request.getOrderNo(), request.getId().toString(), OrderAttachmentType.ORDER_MEMORANDUM_FILE.toString(), request.getStaffName());
        }
    }

    /**
     * 跟进记录设置文本格式
     *
     * @param orderMemorandum 跟进记录
     */
    private void resolveContents(OrderMemorandum orderMemorandum) {
        if (StringUtils.isEmpty(orderMemorandum.getContent())) {
            orderMemorandum.setContents(new ArrayList<>());
        }
        final String separatorChars = "^";

        String replaceContent = orderMemorandum.getContent().replace("\\r\\n", separatorChars).replace("\n", separatorChars);
        String[] split = StringUtils.split(replaceContent, separatorChars);
        orderMemorandum.setContents(Arrays.asList(split));
    }

    private void saveNotifyTaskByResource(OrderMemorandum record) {
        Order order = orderService.findByOrderNo(record.getOrderNo());
        AssertUtils.notNull(order, "订单不存在！");
        switch (record.getType()) {
            case REMARK:
                this.saveOrderRemarkNotifyTaskRecord(order, record);
                break;
            case COMMENT:
                this.saveOrderCommentNotifyTaskRecord(order, record);
                break;
            case LOG:
            default:
                break;
        }
    }

    /**
     * 保存订单跟进记录新增通知任务记录
     * 通知协作人和atUsers
     */
    private void saveOrderRemarkNotifyTaskRecord(Order order, OrderMemorandum record) {
        if (Objects.isNull(order) || Objects.isNull(record)) {
            return;
        }

        List<String> staffs = new ArrayList<>();
        if (StringUtils.isNotEmpty(record.getAtStaffs())) {
            String[] split = StringUtils.split(record.getAtStaffs(), ",");
            staffs.addAll(Arrays.asList(split));
        }

        OrderRevisitLogChangeMessage messageBody = OrderRevisitLogChangeMessage.builder()
                .orderNo(order.getOrderNo())
                .loanUserName(order.getName())
                .operStaffCode(record.getStaffCode())
                .operStaffName(record.getStaffName())
                .atUsers(staffs)
                .build();

        messageSendTaskService.save(MessageSendType.ORDER_REVISIT_LOG_CHANGE_MSG,
                order.getOrderNo(),
                UUID.randomUUID().toString(),
                TopicConsts.ORDER_REVISIT_LOG_CHANGE,
                messageBody);
    }

    /**
     * 保存订单跟进记录评论新增通知任务记录
     * 通知协作人
     */
    private void saveOrderCommentNotifyTaskRecord(Order order, OrderMemorandum record) {
        if (Objects.isNull(order) || Objects.isNull(record)) {
            return;
        }

        OrderRevisitLogChangeMessage messageBody = OrderRevisitLogChangeMessage.builder()
                .orderNo(order.getOrderNo())
                .loanUserName(order.getName())
                .operStaffCode(record.getStaffCode())
                .operStaffName(record.getStaffName())
                .build();

        messageSendTaskService.save(MessageSendType.ORDER_REVISIT_LOG_COMMENT_CHANGE_MSG,
                order.getOrderNo(),
                UUID.randomUUID().toString(),
                TopicConsts.ORDER_REVISIT_LOG_COMMENT_CHANGE,
                messageBody);
    }

    /**
     * 跟进记录设置附件
     *
     * @param orderMemorandum 跟进记录
     */
    @Override
    public void setOrderAttachmentList(OrderMemorandum orderMemorandum) {
        List<OrderAttachment> orderAttachmentList = orderAttachmentService.findByWorkOrderNoAndKey(orderMemorandum.getId().toString(), OrderAttachmentType.ORDER_MEMORANDUM_FILE);
        List<String> imgList = new ArrayList<>(orderAttachmentList.size());
        for (OrderAttachment orderAttachment : orderAttachmentList) {
            //去阿里云服务器换文件地址
            orderAttachment = attachmentService.getUrl(orderAttachment);
            //拿到原文件地址
            imgList.add(orderAttachment.getAccessPath());
        }
        orderMemorandum.setImgList(imgList);
    }

}
